﻿using Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace ApiServer.Utilitys.Filters
{
    /// <summary>
    /// 自定义控制器级别的异步异常捕获器
    /// </summary>
    public class CustomAsyncExecptionFilterAttribute : Attribute, IAsyncExceptionFilter
    {
        private readonly ILogger<CustomAsyncExecptionFilterAttribute> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public CustomAsyncExecptionFilterAttribute(ILogger<CustomAsyncExecptionFilterAttribute> logger)
        {
            this._logger = logger;
        }
        /// <summary>
        /// 控制器级别的异常过滤器，只能铺货控制器内的异常
        /// 作用时将异常封装成自定义的统一的结果数据结构，并记录日志
        /// 自动将结果通过http返回给客户端
        /// </summary>
        /// <param name="context">框架提供的异常上下文</param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                context.Result = new JsonResult(new ApiResult()
                {
                    Success = false,
                    Message = context.Exception.Message
                });
                context.ExceptionHandled = true;
                this._logger.LogError(context.Exception.Message);
            }
          
            await Task.CompletedTask;
        }
    }
}
